package com.yanfan.ibms.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

public class ParamUtils {

    /**
     * 将 HashMap 参数转换为 URL 查询字符串
     *
     * @param params 请求参数，HashMap 类型，键为 String，值为 Object 类型
     * @return 拼接后的查询字符串，例如：name1=value1&name2=value2
     */
    public static String toQueryParamString(HashMap<String, Object> params) {
        if (params == null || params.isEmpty()) {
            return "";
        }

        StringJoiner paramString = new StringJoiner("&");
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            try {
                String key = URLEncoder.encode(entry.getKey(), "UTF-8");
                String value = convertObjectToString(entry.getValue());
                paramString.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("编码错误", e);
            }
        }
        return paramString.toString();
    }

    /**
     * 将 Object 转换为字符串
     *
     * @param obj 需要转换的对象
     * @return 转换后的字符串
     */
    private static String convertObjectToString(Object obj) {
        if (obj == null) {
            return "";
        } else if (obj instanceof String) {
            return (String) obj;
        } else if (obj instanceof Integer || obj instanceof Long || obj instanceof Double || obj instanceof Boolean) {
            return obj.toString();
        } else if (obj instanceof List) {
            // 如果是 List，将其转换为逗号分隔的字符串
            List<?> list = (List<?>) obj;
            StringJoiner sj = new StringJoiner(",");
            for (Object item : list) {
                sj.add(convertObjectToString(item)); // 递归处理列表中的每个元素
            }
            return sj.toString();
        } else {
            // 其他类型，默认调用 toString()
            return obj.toString();
        }
    }
}
